﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using MyFloridaHouse.ServiceConn.DistrBldrSvcRef;
using MyFloridaHouse.libSvOpenDistricts.DataService;
using MyFloridaHouse.libSvOpenDistricts.Districts;
using MyFloridaHouse.libSvOpenDistricts.ViewModel;
using MyFloridaHouse.libSvUtilities.Logging;
using Microsoft.Maps.MapControl;

namespace MyFloridaHouse.SilverlightOpenDistricts
{

    public partial class MainPage
    {
        const int ICON_SIZE_SMALL = 5;
        const int ICON_SIZE_LARGE = 10;
        const int SHOW_ADDRESS_ZOOM_LEVEL = 10;
        const int SHOW_EDGE_ZOOM_LEVEL = 14;



        const Key EASY_CLICK_KEY = Key.Z;
        const Key DATA_FREEZE_KEY = Key.F;


        // set up an interface to our data services
    	private ServiceDAL serviceDAL;
        private ViewModelBase viewModelBase = new ViewModelBase();

		/// <summary>
		/// Gets the custom silverlight parameter from the MyDistrictBuilder.aspx file
		/// <param name="initParams" value="WCFServiceBinidingName=BasicHttpBindingRelativeBinding" />
		/// </summary>
		/// <param name="p">The p.</param>
		/// <returns></returns>
		private string GetParam(string p)
		{
			return App.Current.Resources["WCFServiceBinidingName"] != null ? App.Current.Resources[p].ToString() : "BasicHttpBindingRelativeBinding";
		}


    	private bool InitializeViewModel()
        {
            try
            {
            	var relativeBasicHttpServiceAddress = GetParam("WCFServiceBinidingName");
				serviceDAL = new ServiceDAL(relativeBasicHttpServiceAddress);

				viewModelBase.Initialize(MyXamlMainMap, ChildwindowStackpanel, relativeBasicHttpServiceAddress);


                // set up databinding
                DataGridBorder.DataContext = viewModelBase;
                DataLayoutGrid.DataContext = viewModelBase.dataGridManager;
                RegionShadingControl.DataContext = viewModelBase.regionFill;
                RegionLabelControl.DataContext = viewModelBase.regionLabel;
                LayoutRoot.DataContext = viewModelBase;
                lbx_RegionDataList.ItemsSource = viewModelBase.regionDataList;

                InitializeDiaglogDataContext();

            	return true;
            }
            catch(Exception e)
            {
                Log.HandleInternalError("Problem initializing the view model " + e.Message);
            	return false;
            }
        }


        private void MapZoomToPoint(Location loc, double zoomLevel)
        {
            MyXamlMainMap.SetView(loc, zoomLevel);
        }

        private void MapZoomToShape(BoundingBoxDTO shapeBoundingBox)
        {
            double currentZoom = viewModelBase.mapZoomLevel;
            double currentHeightTop =MyXamlMainMap.BoundingRectangle.Northwest.Latitude;
            double currentHeightBottom = MyXamlMainMap.BoundingRectangle.Southeast.Latitude;
            double currentHeight = currentHeightTop - currentHeightBottom;

            double newHeight = (shapeBoundingBox.northWest.latitude - shapeBoundingBox.southEast.latitude)*1.5;

            double newZoom = 20;
            //if (newHeight < .0006)
            //    newZoom = 20;
            //else if (newHeight < .0012)
            //    newZoom = 19;
            //else if (newHeight < .0024)
            //    newZoom = 18;
            //else if (newHeight < .0048)
            if (newHeight < .0048)
                newZoom = 17;
            else if (newHeight < .0096)
                newZoom = 16;
            else if (newHeight < .0192)
                newZoom = 15;
            else if (newHeight < .0384)
                newZoom = 14;
            else if (newHeight < .1536)
                newZoom = 13;
            else if (newHeight < .3072)
                newZoom = 12;
            else if (newHeight < .75)
                newZoom = 11;
            else if (newHeight < 1.1)
                newZoom = 10;
            else if (newHeight < 2)
                newZoom = 9;
            else if (newHeight < 4)
                newZoom = 8;
            else if (newHeight < 8)
                newZoom = 7;
            else if (newHeight < 11)
                newZoom = 6;
            else
                newZoom = 5;

            Location loc = new Location((shapeBoundingBox.northWest.latitude - shapeBoundingBox.southEast.latitude) / 2 + shapeBoundingBox.southEast.latitude
                                , (shapeBoundingBox.northWest.longitude - shapeBoundingBox.southEast.longitude) / 2 + shapeBoundingBox.southEast.longitude);



            MyXamlMainMap.SetView(loc, newZoom);
        }


        // TODO:  Figure out how to bypass this event handler.  
        // this is taking the place of having xaml bind directly to the CmdDistrictSelect command
        // Problem how do we set a xaml list ItemSource to an ObservableCollection districtList and still be able to access the viewmodel command from xaml
        private void btn_DistrictSelect_Click(object sender, RoutedEventArgs e)
        {
            int districtID = ((District)((Button)sender).Tag).districtID;
            viewModelBase.districtPlan.SetActiveDistrict(districtID);
        }

        // TODO:  Figure out how to bypass this event handler.  
        // this is taking the place of having xaml bind directly to the CmdDistrictStragglerSelect command
        // Problem how do we set a xaml list ItemSource to an ObservableCollection districtList and still be able to access the viewmodel command from xaml
        private void btn_DistrictSubshape_Click(object sender, RoutedEventArgs e)
        {
            DistrictSubShapeMetadata subShape = ((DistrictSubShapeMetadata)((Button)sender).Tag);
            MapZoomToShape(subShape.boundingBox);            
        }

        private void btn_DistrictExtent_Click(object sender, RoutedEventArgs e)
        {
            int selectedDistrictIndex = ((int)((Button)sender).Tag);
            BoundingBoxDTO boundingBox = viewModelBase.districtPlan.selectedDistrictBoundingBox;
            if (boundingBox == null)
            {
                MessageBox.Show("No Shapes in District");
            }
            else
            {
                MapZoomToShape(boundingBox);
            }
        }
    }
}
